import { addZero } from './_'

// date.js
/* jshint esversion: 6 */
export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
}

function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}
/**
 * safri获取时间
 * @param {String} time 未初始化时间
 */
export const safarigetdate = (time) => {
  return new Date(time.toString().replace(/[-]/g, '/'))
}
export const HMS2S = (val, gapval) => {
  try {
    return val
      .split(gapval)
      .map((e, i) =>
        i === 0 ? +e * 60 * 60 : i === 1 ? +e * 60 : i === 2 ? +e : 1
      )
      .reduce((a, b) => a + b);
  } catch (error) {
    console.log(error);
    return 0;
  }
};
export const S2HMS = (n) => {
  return {
    h: addZero(((n / 60 / 60)) | 0, 2),
    m: addZero((n / 60 % 60) | 0, 2),
    s: addZero((n % 60) | 0, 2)
  }
}
export const Timekeep = () => {
  var keppTwoNumber = n => {
    return (n + "").length === 1 ? `0${n}` : n;
  };
  var get_date_s = n => {
    return keppTwoNumber(n % 60);
  };
  var get_date_m = n => {
    return keppTwoNumber(((n % 3600) / 60) | 0);
  };
  var get_date_h = n => {
    return keppTwoNumber((n / (60 * 60)) | 0);
  };
  let type = "";
  let nextNum = 0;
  let userCallFunc;
  // 任务执行列表，控制start进来生命周期
  let taskList = [];
  let count = (n, callback, taskId) => {
    setTimeout(() => {
      if (type === "start" || type === "continue") {
        nextNum = n + 1;
        callback({
          h: get_date_h(nextNum),
          m: get_date_m(nextNum),
          s: get_date_s(nextNum)
        });
        count(nextNum, callback, taskId);
      }
    }, 1e3);
  };
  return {
    getTaskId: () => ((+new Date() + Math.random() * 100) | 0) + "",
    start(_userCallFunc, { n, taskId }) {
      userCallFunc = _userCallFunc;
      type = "start";
      if (taskId) {
        if (taskList.includes(taskId)) {
          return;
        }
      }
      taskId && taskList.push(taskId);
      // filter((item, index ,arr)=>arr.indexOf(item) === index)
      count(n || 0, userCallFunc, taskId);
    },
    stop() {
      if (!userCallFunc) {
        console.error("未启动，请先启动");
        return;
      }
      type = "stop";
    },
    continue() {
      if (!userCallFunc) {
        console.error("未启动，请先启动");
        return;
      }
      type = "continue";
      count(nextNum, userCallFunc);
    },
    end(taskId) {
      // 启用任务管理的话，销毁的时候移除任务
      if (taskId) {
        taskList = taskList.filter(id => id !== taskId);
      }
      if (!userCallFunc) {
        console.error("未启动，请先启动");
        return;
      }
      // 清空释放资源
      type = null;
      nextNum = null;
      userCallFunc = null;
    }
  };
};

export const getDateDiff = dateTimeStamp => {
  let result;
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;
  if (diffValue < 0) {
    return;
  }
  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  if (monthC >= 1) {
    result = "" + parseInt(monthC) + "月前";
  } else if (weekC >= 1) {
    result = "" + parseInt(weekC) + "周前";
  } else if (dayC >= 1) {
    result = "" + parseInt(dayC) + "天前";
  } else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前";
  } else if (minC >= 1) {
    result = "" + parseInt(minC) + "分钟前";
  } else result = "刚刚";
  return result;
};

export const Fresh = (callBacks = []) => {
  let len;
  const _fresh = (endtime, cb, setReVal, dateIndex) => {
    // start end date
    const date = +new Date(),
      leftsecond = ((endtime - date) / 1000) | 0,
      // funcs
      isStop = Boolean(leftsecond > 0),
      result = state => val => ({ state, val });
    // vars
    let dataObj = { d: void 0, h: void 0, m: void 0, s: void 0 },
      re = void 0;

    // default result val format
    if (!setReVal) setReVal = ({ d, h, m, s }) => `${d}天${h}小时${m}分${s}秒`;
    //  computed date
    dataObj = {
      d: parseInt(leftsecond / 3600 / 24),
      h: parseInt((leftsecond / 3600) % 24),
      m: parseInt((leftsecond / 60) % 60),
      s: parseInt(leftsecond % 60)
    };
    // set result
    re = isStop ? result(true)(setReVal(dataObj)) : result(false)("结束");
    // stop
    isStop || callBacks.splice(dateIndex, 1);
    // cb
    cb(re);
  };

  // export
  const init = (endDateVal, cb, setReVal) => {
    callBacks.push([endDateVal, cb, setReVal]);
  };

  // export
  const start = () => {
    const palyInterval = () => {
      if (callBacks.length == 0) {
        clearInterval(sh);
        return;
      }
      callBacks.forEach((params, index) => {
        len = len ? len : params.length;
        params[len] = index;
        _fresh(...params);
      });
    };
    palyInterval();
    // definition Interval
    const sh = setInterval(palyInterval, 1000);
  };
  const end = () => {
    callBacks = []
  }
  return {
    add: init,
    start,
    end
  };
};

/**
 * 计时器  多个切换
 */
export const Timekeeps = () => {
  var keppTwoNumber = n => {
    return (n + "").length === 1 ? `0${n}` : n;
  };
  var get_date_s = n => {
    return keppTwoNumber(n % 60);
  };
  var get_date_m = n => {
    return keppTwoNumber(((n % 3600) / 60) | 0);
  };
  var get_date_h = n => {
    return keppTwoNumber((n / (60 * 60)) | 0);
  };
  let type = "";
  let nextNum = 0;
  let userCallFunc;
  // 任务执行列表，控制start进来生命周期
  let taskList = [];
  let runing = false
  let count = (n, callback, taskId) => {
    setTimeout(() => {
      // console.log('time              taskList')
      // console.log(taskList)
      taskList.forEach((task) => {
        let { n, id, func } = task
        task.n = n + 1
        if (type === "start" || type === "continue") {
          func({
            h: get_date_h(n + 1),
            m: get_date_m(n + 1),
            s: get_date_s(n + 1)
          });
        }
      })
      count()
    }, 1e3);
  };
  return {
    getTaskId: () => ((+new Date() + Math.random() * 100) | 0) + "",
    start(_userCallFunc, { n, taskId }) {
      // userCallFunc = _userCallFunc;
      // debugger
      type = "start"
      let Copy = e => JSON.parse(JSON.stringify(e))
      let taskToken = ({
        id: taskId,
        n: n || 0,
        func: _userCallFunc
      })
      // console.log('----taskList---')
      // console.log(taskList)
      // 修改数据
      if (taskId && taskList.map(e => e.id).includes(taskId)) {
        taskList.map(e => {
          if (e.id === taskId) {
            return taskToken
          }
          return e
        })
        return
      }
      taskList.push(taskToken)
      // 开启时间秒频率执行
      if (!runing) {
        count()
        runing = true
      }
      // taskId && taskList.push(taskId);
      // filter((item, index ,arr)=>arr.indexOf(item) === index)
      // count(n || 0, userCallFunc, taskId);
    },
    stop() {
      if (!userCallFunc) {
        console.error("未启动，请先启动");
        return;
      }
      type = "stop";
    },
    continue() {
      if (!userCallFunc) {
        console.error("未启动，请先启动");
        return;
      }
      type = "continue";
      count(nextNum, userCallFunc);
    },
    end(taskId) {
      // 启用任务管理的话，销毁的时候移除任务
      if (taskId) {
        taskList = taskList.filter(e => e.id !== taskId);
      }
      if (!userCallFunc) {
        console.error("未启动，请先启动");
        return;
      }
      // 清空释放资源
      type = null;
      nextNum = null;
      userCallFunc = null;
    }
  };
};
